package com.xaicode.learn.java.forkjoin;

import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author Locker cjxia@isoftstone.com
 * @version 1.0
 */
public class ForkJoinTaskDemo2 {

    public static void main(String[] args) {
        Integer count = new ForkJoinPool()
                .invoke(new CountingTask(Paths.get("c:/Locker")));
        System.out.println("c:/Locker file count: " + count);
    }

    static class CountingTask extends RecursiveTask<Integer> {
        private Path path;

        public CountingTask(Path path) {
            this.path = path;
        }

        @Override
        protected Integer compute() {
            int count = 0;

            List<CountingTask> subTasks = new ArrayList<>();
            try {
                DirectoryStream<Path> ds = Files.newDirectoryStream(path);
                for (Path subPath : ds) {
                    if (Files.isDirectory(subPath)) {
                        subTasks.add(new CountingTask(subPath));
                    } else {
                        count++;
                    }
                }
                if (!subTasks.isEmpty()) {
                    for (CountingTask subTask : invokeAll(subTasks)) {
                        count += subTask.join();
                        System.out.println(count + " " + subTask.path);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return count;
        }
    }

}
